/**
 * 根据要求，将特定的对象解析成数据包。
 * Created by macos on 14/10/28.
 */

var EventEmitter = require('events').EventEmitter;
var util = require('util');
var _ = require('lodash');

var slice = Function.prototype.call.bind(Array.prototype.slice);

(function() {

  var root = this;

  function MessageEncoder(conn) {
    EventEmitter.call(this);

    var self = this;
    self._conn = conn;
    self._connected = false;

    //复制net.socket的属性到MessageEncoder
    _.forEach([
      'bufferSize',
      'bytesRead',
      'bytesWritten',
      'localAddress',
      'localPort',
      'remoteAddress',
      'remotePort'
    ], function(property) {
      self.__defineSetter__(property, function(v) {
        self._conn[property] = v;
      });
      self.__defineGetter__(property, function() {
        return (self._conn[property]);
      });
    });

    //复制net.socket的事件到MessageEncoder
    _.forEach([
      'connect',
      'end',
      'timeout',
      'drain',
      'error',
      'close'
    ], function(event) {
      self._conn.on(event, function() {
        var args = slice(arguments);
        args.unshift(event);
        self.emit.apply(self, args);
      });
    });
  }
  util.inherits(MessageEncoder, EventEmitter);

  MessageEncoder.prototype.isConnected = function(connected) {
    this._connected = connected;
  }

  //复制srv的方法到Server
  _.forEach([
    'address',
    'connect',
    'destroy',
    'end',
    'pause',
    'ref',
    'resume',
    'setEncoding',
    'setKeepAlive',
    'setNoDelay',
    'setTimeout',
    'unref',
    'write'
  ], function(method) {
    MessageEncoder.prototype[method] = function() {
      this._conn[method].apply(this._conn, arguments);
    };
  });

  MessageEncoder.prototype.writeHex = function writeHex(hexStr) {
    if (this._connected) {
      this.write(hexStr, 'hex');
    } else {
      this.emit('error', 'socket was closed')
    }
  }



  /**
   *
   * @param obj
   * @param affix
   */
  MessageEncoder.prototype.writeObj = function writeObj(obj, affix) {

    var hexStr = "";
    for (var k in obj) {
      hexStr = hexStr + obj[k];
    }

    if (_.isFunction(affix)) {
      this.write(affix(hexStr), 'hex');
    } else {
      this.write(hexStr, 'hex');
    }
  }

  module.exports = {
    MessageEncoder: MessageEncoder
  }
})();